package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.OfficeDao;
import com.seadragon.app.ksr.model.Business;
import com.seadragon.app.ksr.model.Office;

@Repository("officeDao")
public class OfficeDaoJpaImpl extends AbstractJpaDao implements OfficeDao {
	@Override
	public Office findById(long id) {
		return entityManager.find(Office.class, id);
	}

	@Override
	public Office update(Office office){
		entityManager.merge(office);
		return office;
	}

	@Override
	public List<Office> findAll(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Office> cq = cb.createQuery(Office.class);
		Root<Office> root = cq.from(Office.class);
		cq.select(root);
		TypedQuery<Office> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

	@Override
	public List<Office> findAllBy(Business business) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Office> cq = cb.createQuery(Office.class);
		Root<Office> root = cq.from(Office.class);
		cq.select(root);
		cq.where(cb.equal(root.get("business"), business));
		return entityManager.createQuery(cq).getResultList();
	}

	@Override
	public void save(Office office) {
		entityManager.persist(office);
	}

	@Override
	public void delete(Office office) {
		entityManager.remove(office);
	}

	@Override
	public List<Office> findAllBy(Business business, int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Office> cq = cb.createQuery(Office.class);
		Root<Office> root = cq.from(Office.class);
		cq.select(root);
		cq.where(cb.equal(root.get("business"), business));
		TypedQuery<Office> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);

		return tq.getResultList();
	}

}
